package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Interface {



	public static void main(String[] args){

		Client client = null;
		int i = 0;
		client = new Client();
		boolean ok = true;
		BufferedReader inputReader=null;
		String UUIDsAndResponses="";
		String[] splitResponse=null;
		String[] UUIDAndResponse=null;

		//Read the arguments
		for(i = 0; i<args.length;i++){
			if(args[i].equals("-s")){
				i++;
				//If the ip isn't well formated, return false
				ok &= client.setIpScheduler(args[i]);
			}

			if(args[i].equals("-w")){
				i++;
				//If the path doesn't lead to a file return false
				ok &=client.setPathToWorkLoad(args[i]);
			}
		}
		//If everything is ok then process
		if(ok){
			client.sendTasksToScheduler();
		}else{
			//else stop the program
			System.out.println("Bad arguments");
			return;
		}

		//Prepare to read the responses through the socket
		try {
			inputReader = new BufferedReader(new InputStreamReader(client.getSocket().getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int j=0;
		i=0;
		//While there are still some tasks that haven't respond 
		try {
			while(i <client.nbTasks()){
				//Read the line from the socket (formated as "UUID/response UUID/response etc")
				UUIDsAndResponses = inputReader.readLine();
				splitResponse = UUIDsAndResponses.split(" ");
				//For each unique UUID, find the task and set the response
				for(j = 0; j<splitResponse.length;j++){
					UUIDAndResponse = splitResponse[j].split("/");
					client.getTasks().get(UUIDAndResponse[0]).setResult(Integer.parseInt(UUIDAndResponse[1]));
					//Increment the number of tasks that has responded.
					i++;
				}
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
